package com.laikan.library.utils;

import android.app.Activity;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.wifi.WifiManager;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.TextUtils;
import android.util.Patterns;
import org.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

public class DeviceUtil {

    /**
     * 获取手机imei
     *
     * @return
     */
    public static String getImei(Context activity) {

        return ((TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
    }

    /**
     * 获取手机imsi
     *
     * @return
     */
    public static String getImsi(Context activity) {

        return ((TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
    }

    /**
     * 获取手机号码
     *
     * @return
     */
    public static String getPhoneNumber(Activity activity) {

        return ((TelephonyManager)activity.getSystemService(Context.TELEPHONY_SERVICE)).getLine1Number();
    }

    /**
     * 获取手机型号
     *
     * @return
     */
    public static String getDeviceType() {

        return android.os.Build.DEVICE;
    }

    /**
     * 获取Android版本号
     *
     * @return
     */
    public static String getAndroidVersion() {

        return android.os.Build.VERSION.RELEASE;
    }

    public static String getDeviceInfo(Context context) {

        try {
            JSONObject json = new JSONObject();
            TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
            String device_id = tm.getDeviceId();
            WifiManager wifi = (WifiManager)context.getSystemService(Context.WIFI_SERVICE);
            String mac = wifi.getConnectionInfo().getMacAddress();
            json.put("mac", mac);
            if (TextUtils.isEmpty(device_id)) {
                device_id = mac;
            }
            if (TextUtils.isEmpty(device_id)) {
                device_id = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            }
            json.put("device_id", device_id);
            return json.toString();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static final SimpleDateFormat DATE_TIME_FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取手机设备IMEI
     *
     * @param context
     *
     * @return IMEI串
     */
    public static String getDeviceID(Context context) {

        TelephonyManager telephonyManager = (TelephonyManager)context.getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
        return telephonyManager.getDeviceId();
    }

    /**
     * // 在application应用<meta-data>元素。
     *
     * @param context
     * @param metaDataKey
     *
     * @return
     */
    public static String getMetaDataStringValue(Context context, String metaDataKey) {

        ApplicationInfo appInfo = null;
        try {
            appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (appInfo != null) {
            return appInfo.metaData.getString(metaDataKey);
        }
        return "";
    }

    public static String getSpecialBookId(Context context, String metaDataKey){
        String metaValue = getMetaDataStringValue(context, metaDataKey);
        String[] strings = metaValue.split("_");

        if (strings.length == 3 && strings[1].equals("special")){
            return strings[2];
        }else {
            return null;
        }
    }

    public static boolean getMetaDataBooleanValue(Context context, String metaDataKey) {

        ApplicationInfo appInfo = null;
        try {
            appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
        }catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (appInfo != null) {
            return appInfo.metaData.getBoolean(metaDataKey);
        }
        return true;
    }

    /**
     * 判定号码是否为手机号码
     *
     * @param mobiles
     *
     * @return
     */
    public static boolean isMobileNO(String mobiles) {

        try {
            String number = mobiles.replaceAll("-", "").replaceAll(" ", "");
            number = number.substring(number.length() - 11, number.length());
            //			Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,2,5-9]))\\d{8}$");
            Pattern p = Pattern.compile("^((13[0-9])|(15[0-9])|(17[0-9])|(18[0-9]))\\d{8}$");
            Matcher m = p.matcher(number);
            return m.matches();
        }catch (Exception e) {
            return false;
        }
    }

    /**
     * 格式化字符串中的 某些特定字符的颜色
     * <string name="html_string_temp">TEMP1&lt;font color=#ff8800>%1$d&lt;/font>TEMP2&lt;font color=#ff8800>%2$s&lt;/font>，&lt;font color=#ff8800>%3$d&lt;/font>TEMP3</string>
     * @param context
     * @param resourceID
     * @param formatArgs
     *
     * @return
     */
    public static CharSequence getHtmlFormatedString(Context context, int resourceID, Object... formatArgs) {

        CharSequence str = "";
        str = Html.fromHtml(context.getResources().getString(resourceID, formatArgs));
        return str;
    }

    public static String optNUmber(String mobiles) {

        String number = mobiles.replaceAll("-", "").replaceAll(" ", "");
        number = number.substring(number.length() - 11, number.length());
        return number;
    }

    public static String getRealPhoneNumber(String number) {

        if (isMobileNO(number)) {
            return optNUmber(number);
        }
        return number.replaceAll("-", "").replaceAll(" ", "");
    }

    public static String getDate(String longtime) {

        SimpleDateFormat sfd = new SimpleDateFormat("MM/dd HH:mm");
        Date date = new Date(Long.parseLong(longtime));
        String time = sfd.format(date);
        return time;
    }

    public static boolean isPhoneNUmber(String number) {

        Matcher match = Patterns.PHONE.matcher(number);
        boolean bool = match.matches();
        return bool;
    }

    //	// // 设置请求头设置通用的请求头
    //	public static Map<String, String> getRequestCommonHeader(){
    //
    //		// 设置字符集为UTF-8,并采用gzip压缩传输
    //		Map<String, String> headers = new HashMap<String, String>();
    //		headers.put("Charset", "UTF-8");
    //		headers.put("Accept-Encoding", "gzip");
    //		String appVersion = CheddApplication.getInstance().getCurrentAppVer();
    //		String umChannelId = CheddUtils.getChannelValue(CheddApplication.getInstance().getApplicationContext());
    //		String ua = DeviceUtil.getDeviceType() + DeviceUtil.getAndroidVersion();
    //		headers.put("version", appVersion);// 设备型号
    //		headers.put("ua", ua);// 设备型号
    //		headers.put("channelid", umChannelId);// 渠道号
    //		headers.put("os", "android");
    //		return headers;
    //	}

    public static byte[] gzipDecompress(byte[] data) throws IOException {

        GZIPInputStream gzip = new GZIPInputStream(new ByteArrayInputStream(data));
        ByteArrayOutputStream o = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int iRead = 0;
        while (0 < (iRead = gzip.read(buffer))) {
            o.write(buffer, 0, iRead);
        }
        return o.toByteArray();
    }


    //	// 退出应用
    //	public static void exitApp(){
    //
    //		LocalActivityMgr.getInstance().clearActivity();
    //		EventBusFactory.COMMON.unregister(GlobalEventHandler.getInstance());
    //		System.exit(0);
    //	}


}
